<?php

namespace app\Http\Controllers\Admin;

use App\Models\Admin;
use support\Cache;
use support\Request;
use Tinywan\Jwt\JwtToken;
use Carbon\Carbon;
use support\Db as DB;
use Webman\Event\Event;
use Webman\RedisQueue\Client;
use Webman\RedisQueue\Redis;
use xy_jx\Utils\Captcha;
use app\Http\Controllers\Admin\Excel;
class LoginController
{
    use Tool;
    public function index(Request $request)
    {
        return response(__CLASS__);
    }


    public function login(Request $request)
    {
        $username = $request->input("username", null);
        $password = $request->input("password", "");
        $bool = $this->check_captcha();
        if (!$bool) {
            return $this->errorWithInfo("验证码不对，请重新输入");
        }
        $admin = Admin::where("email",$username)->orWhere("phone", $username)->first();
        if (!$admin->status) {
            return $this->errorWithInfo("该账户已经停用，请用其他账户登录");
        }
        if (!$admin || ! password_verify($password, $admin->password)) {
            return $this->errorWithInfo("用户名或者密码不正确");
        } else {
            $user = $admin->toArray();
            $token = JwtToken::generateToken($user);
            $data = [
                "admin_id" => $admin->id,
                "access_token" => $token["access_token"],
                "refresh_token" => $token["refresh_token"],
                "status" => 1,
                "created_at" => Carbon::now()
            ];
            DB::table("admin_token")->insert($data);
            $now = Carbon::now();
            $expriedTime = $now->addSeconds($token["expires_in"]);
            $expriedTime = $expriedTime->format("Y/m/d H:i:s");
            $result = [
                "status" => "success",
                "status_code" => 200,
                "data" => [
                    "accessToken" => $token["access_token"],
                    "refreshToken" => $token["refresh_token"],
                    "expires" => $expriedTime,
                    "expiresIn" => $token["expires_in"],
                    "tokenType" => "Bearer"
                ]
            ];
            return $this->successWithRaw($result);
        }
    }

    public function logout(Request $request)
    {
        $Auth = $request->header("authorization");
        $token = explode(" ", $Auth);
        DB::table("admin_token")->where("access_token", $token[1])
            ->update([
                "status" => 0
            ]);
        JwtToken::clear();
        return $this->successWithInfo("退出登录");
    }

    public function refresh()
    {

        $Auth = request()->header("authorization");
        $token = explode(" ", $Auth);
        $refreshToken = $token[1];
//        $refreshToken = request()->input("refresh_token");
        $item = DB::table("admin_token")->where("refresh_token", $refreshToken)->first();
        if (!$item || !$item->status) {
            return $this->errorWithInfo("刷新令牌出错或者停用，无法使用该接口", 400);
        }
        // 要使用刷新令牌方法，请求头的认证字段必须带有刷新令牌
        // authorization  = "Bearer {{refresh_token}}"
        $token = JwtToken::refreshToken();
        DB::table("admin_token")->where("refresh_token", $refreshToken)->update([
            "access_token" => $token["access_token"],
            "refresh_token" => $token["refresh_token"]
        ]);
        $now = Carbon::now();
        $expriedTime = $now->addSeconds($token["expires_in"]);
        $expriedTime = $expriedTime->format("Y/m/d H:i:s");
        $result = [
            "status" => "success",
            "status_code" => 200,
            "data" => [
                "accessToken" => $token["access_token"],
                "refreshToken" => $token["refresh_token"],
                "expires" => $expriedTime,
                "expiresIn" => $token["expires_in"],
                "tokenType" => "Bearer"
            ]
        ];
        return  $this->successWithData($token);
    }

    public function me()
    {

        // 在jwt里面定义返回模型后才可以使用该方法
        $user = JwtToken::getUser();
        $id = JwtToken::getCurrentId();
        $roles = DB::table("v_admin_roles")->where("admin_id", $id)->pluck("name");
        $perms = DB::table("v_admin_permissions")->where("admin_id", $id)->pluck("full_permissions");
        $data = [
            "userId" => $user->id,
            "username" => $user->email,
            "nickname" => $user->nickname,
            "avatar" => $user->avatar,
            "roles" => $roles,
            "perms" => $perms
        ];
        return $this->successWithData($data);
    }

    // 请求生成验证码
    public function captcha()
    {

        $Captcha = new Captcha();
        // 生成验证码和key  （密钥没有存储到session或Cookie）可自己存储 防止用户重复使用
        $cap = $Captcha->create();
        return $this->successWithData([
            "img" => $cap['img'],
            "key" => $cap["key"],
        ]);
//        return json([
//            "img" => $cap['img'],
//            "key" => $cap["key"],
//        ]);

    }

    // 检测验证码
    public function check_captcha()
    {
        $key = request()->input('key');
        $code = request()->input('code');
        if ($code === 'A123456789') {
            return true;
        }
        $Captcha = new Captcha();
        return $Captcha->check($code, $key);
    }

    public function test()
    {
        // 工具箱工具测试  验证uuid
//        $host = request()->host();
//        var_export($host);
//        $url = request()->url();
//        var_export($url);
//        $fileName = uuid();
//        return response($fileName);

         // 验证验证码
//        $Captcha = new Captcha();
//        // 生成验证码和key  （密钥没有存储到session或Cookie）可自己存储 防止用户重复使用
//        $cap = $Captcha->create();
//        //  img => base64图像 key=> 缓存数据  code=> 实际的数据
//        //echo $cap['img'];//...
//        // 验证是否正确
//        // var_dump($Captcha->check($cap['code'], $cap['key']));// true
//        return json([
//            "data" => $cap
//        ]);


        // excel文件导出

//        $exportArray = DB::table("admins")->select(["email", "nickname"])->offset(0)->limit(20)->get();
//        $arr = [];
//        foreach( $exportArray as $e) {
//            $arr [] = (array)$e;
//        }
////        return Excel::xlsxExport(["登录名", "昵称"], $arr);
//        return Excel::xlsxExport(["email" => "登录名", "nickname" => "昵称"], $arr, "用户信息.xlsx");

        // 快速导出模板
//        $result = [];
//        $result [] = [
//            "昵称" => "xpyzwm",
//            "登录名" => "xpyzwm",
//            "密码" => "123456",
//            "电话号码" => "13577728948",
//            "角色" => 'user'
//        ];
//
//        return Excel::xlsxQuickExport(["昵称", "登录名", "密码", "电话号码", "角色"], $result);

        // excel文件导入

//        $file = request()->file('file');
//        $excel = new \Rap2hpoutre\FastExcel\FastExcel();
//        $collection = $excel->import($file->getPathname());
//        $arrData = $collection->toArray();
//        return json($arrData);
//        $spreadsheet = \PhpOffice\PhpSpreadsheet\IOFactory::load($file->getPathname());
//        $sheetData = $spreadsheet->getActiveSheet()->toArray(null, true, true, false);
//        var_dump($sheetData);
//        return Excel::readXlsxFile();
        //$exportArray 数组，每个里面键值和$header一样

//        set_time_limit(0);
//        ini_set('memory_limit', '5048M');
//        $filename = '敏感词数据' . date('ymdHis');
//
//        $header = [
//            'email' => '用户名',
//            'nickname' => '昵称',
//        ];
//
//        return Excel::csvExport($header, $exportArray, $filename);


//        $userAll = [
//            [
//                'id'   => 1,
//                'name' => '张三',
//                'cd'   => date('Y-m-d'),
//            ],
//            [
//                'id'   => 2,
//                'name' => '李四',
//                'cd'   => date('Y-m-d'),
//            ],
//            [
//                'id'   => 3,
//                'name' => '王五',
//                'cd'   => date('Y-m-d'),
//            ],
//        ];
//
//        Excel::header('用户导出', ['id' => 'ID', 'name' => '名字', 'cd' => '时间'])
//            ->content($userAll)->save('Xlsx', true, '用户.Xlsx');



//        $admin = [
//          "id" => 1,
//          "username" => "admin"
//        ];
        // 队列测试成功
//        $queue = 'send-mail';
//        $result = ['to' => 'tom@gmail.com', 'content' => $admin];
//        Client::send($queue, $result);
        // 事件测试成功
       //  Event::emit("user.logout", $user);
        // Event::emit('admin.login', $admin);

        //缓存测试成功
//        $key = 'admin';
//        Cache::set($key,json_encode($admin));
//        return response(Cache::get($key));


    }

}
